package com.ndbg.demo.gateway.user;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ndbg.demo.acting.UserServiceHandler;
import com.ndbg.demo.model.User;
import com.ndbg.demo.service.user.service.IUserService;
import com.ndbg.demo.service.user.service.impl.UserServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.cglib.proxy.Proxy;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author auther
 * @since 2021-09-20
 */
@RestController
@RequestMapping("/test/demo/user")
public class UserController {

    private IUserService userService;


    public UserController(IUserService userService) {
        UserServiceHandler handler = new UserServiceHandler(userService);
        this.userService = (IUserService) Proxy.newProxyInstance(handler.getClass().getClassLoader(), UserServiceImpl.class.getInterfaces(),handler);
    }

    /**
     * 新增用户（方便测试才用get）
     *
     * @param
     */
    @GetMapping(path = "/add")
    @ApiOperation(value = "新增用户", notes = "新增用户")
    public void list() {
        userService.add();
    }

    /**
     * 导入
     * @param file
     */
    @PostMapping("/import")
    public void importUser(@RequestPart("file") MultipartFile file) {
        //Workbook workbook = PoiSXSSFWorkbookExcel.getWorkbook(file);
        //// 获取第一个表格
        //Sheet sheet = workbook.getSheetAt(0);
        //for (int i = 2; i <= sheet.getLastRowNum(); i++) {
        //    Row row = sheet.getRow(i);
        //}
        XSSFWorkbook workBook = null;
        try (InputStream inputStream = file.getInputStream()){
            //读取工作簿
            workBook = new XSSFWorkbook(inputStream);
            //读取工作表
            XSSFSheet sheet = workBook.getSheetAt(0);

            sheet.getLastRowNum();
            //读取行
            XSSFRow row = sheet.getRow(0);
            row.getLastCellNum();
            //读取单元格
            XSSFCell cell = row.getCell(0);
            String value = cell.getStringCellValue();
            // 业务处理 ...

        } catch (IOException e) {
            System.out.println("读取excel失败");
        }finally {
            if(workBook != null){
                //关闭工作簿
                try {
                    workBook.close();
                } catch (IOException e) {
                    System.out.println("关闭工作簿失败");
                }
            }
        }
    }



    @GetMapping(value = "/page")
    public IPage<User> getPageList() {
        Page<User> page = new Page<>();
        page.setCurrent(1);
        page.setSize(10);
        return userService.getPage(page);
    }
}

